package com.bytecodezz.idcard

import android.content.Context
import android.graphics.Bitmap
import com.googlecode.tesseract.android.TessBaseAPI
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

/**
 * @author: bytecodezz
 * @version: 1.0
 * @time: 2021/7/7 15:22
 * @package: com.bytecodezz.idcard
 *
 * @description:
 *
 */
class IDCardTools {
    var DEBUG: Boolean = true
    private var baseApi: TessBaseAPI? = null

    init {
        System.loadLibrary("IDCardScan")
    }

    companion object {
        fun openCVVersion() {
            let { }
        }
    }

    fun getTxtByBitmap(context: Context, src: Bitmap, result: (String) -> Unit) {
        baseApi = TessBaseAPI()
        var `is`: InputStream? = null
        `is` = context.getAssets().open("cn.traineddata")
        val file = File("/sdcard/tess/tessdata/cn.traineddata")
        if (!file.exists()) {
            file.parentFile.mkdirs()
            val fos = FileOutputStream(file)
            val buffer = ByteArray(2048)
            var len: Int
            while (`is`.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.close()
        }
        `is`.close()
        baseApi?.init("/sdcard/tess", "cn")

        // 识别Bitmap中的图片
        baseApi?.setImage(src)
        result.invoke(baseApi!!.utF8Text)
        baseApi!!.clear()
    }

    external fun versionNative()

    external fun getIDNumberBitmap(src: Bitmap, config: Bitmap.Config): Bitmap
//    external fun getIDNameBitmap(src: Bitmap, config: Bitmap.Config): Bitmap
//    external fun getIDAgeBitmap(src: Bitmap, config: Bitmap.Config): Bitmap
}